package com.zxq.factory.decoder.impl;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import com.zxq.factory.decoder.IFieldDecoder;
import com.zxq.factory.encoder.impl.DoubleFieldEncoder;

public class DoubleDecoder implements IFieldDecoder<Double> {

    LongDecoder longDecoder = new LongDecoder();


    @Override
    public Double decoder(byte[] msg) {
        if(msg.length != 8) {
            System.out.println("double 只支持8字节");
            return 0.0;
        }
        //正负数标记
        Integer mark = 1;
        Integer exponent = 0;

        byte highByte = 0;
        byte lowByte = 0;
        //63 || 62,61,60,59,58,57,56----55,54,53,52 || 51,50,49,48
        //msg[0] 63 - 56   <<1  62 - 56
        //msg[1] 55 - 48   >>4  55 - 52 -> 55,0,0,0,0,54,53,52
        highByte = msg[0];
        if(highByte < 0) {
            mark = -1;
            highByte = (byte) ~(highByte -1);
        }
        lowByte = (byte) (msg[1] >> 4);
        Integer shiftExponent = highByte * 16 + lowByte;
        exponent = shiftExponent - 1023;
        byte temp = (byte) (msg[1] % 16);

        byte[] longValueBuff = new byte[7];
        longValueBuff[0] = temp;
        longValueBuff[1] = msg[2];
        longValueBuff[2] = msg[3];
        longValueBuff[3] = msg[4];
        longValueBuff[4] = msg[5];
        longValueBuff[5] = msg[6];
        longValueBuff[6] = msg[7];


        Long longValue = longDecoder.decoder(longValueBuff);

        //小数点右后，原来int值，变化成的float数值,1.xxx * Math.pow(2,exponent)中的 1.xxx的值
        Double ratioValue = longValue * Math.pow(0.5,  52) + 1;
        System.out.println("ratioValue:" + ratioValue);
        //小数点右后，原来int值，变化成的float数值,1.xxx * Math.pow(2,exponent)中的 1.xxx的值

        Double doubleValue = mark * Math.pow(2,exponent) * ratioValue;

        return doubleValue;
    }

//      public static void main(String[] args) {
//        Double dValue = 10.01;
//        System.out.println("dValue:" + dValue);
//        DoubleFieldEncoder doubleFieldEncoder = new DoubleFieldEncoder();
//        byte[] hexBuff = doubleFieldEncoder.encoder(dValue,8);
//        System.out.println("doubleHex:" + HexBin.encode(hexBuff));
//        DoubleDecoder doubleDecoder = new DoubleDecoder();
//        Double value = doubleDecoder.decoder(hexBuff);
//        System.out.println("value:" + value);
//    }



}
